//
//  AddressBookViewModel.swift
//  MoyoungDevice
//
//  Created by 易先生 on 2022/8/26.
//

import UIKit
import RxCocoa
import RxSwift
import CRPEarPhone
import EarbudsDatabase

public class AddressBookViewModel: ViewModel {

    public let itemsRelay = BehaviorRelay<[ContactModel]>(value: [])
    
    public var items: [ContactModel] {
        return self.itemsRelay.value
    }
    public let maxCount = BehaviorRelay<Int>(value: 8)
    
    private var oldContacts: [ContactModel] = []
    
    public override init() {
        super.init()
        
//        BluetoothManager.shared.queryContactConfig()
//            .subscribe(onNext: { [weak self] config in
//                guard let `self` = self else { return }
//                
//                self.maxCount.accept(config.contactMax)
//                
//                let items = Array(dataBase.getAll(type: ContactModel.self).prefix(config.contactMax))
//                self.itemsRelay.accept(items)
//                self.oldContacts = items
//                
//            }).disposed(by: rx.disposeBag)
        
        let items = Array(EasepodsDB.getAll(type: ContactModel.self).prefix(maxCount.value))
        self.itemsRelay.accept(items)
        self.oldContacts = items
    }
   
    public func numberOfRowsInSection() -> Int {
        return items.count
    }
    
    public func cellModelForRowAtIndexPath(indePath: IndexPath) -> ContactModel {
        let model = self.items[indePath.row]
        return model
    }
    
    public func addContacts(models: [ContactModel]) {
        guard models.count <= maxCount.value else {
            return
        }
        self.itemsRelay.accept(models)
    }
    
    public func removeCardModel(indexPath: IndexPath) {
        var items = self.items
        items.remove(at: indexPath.row)
        self.itemsRelay.accept(items)
    }
    
    public func moveRowAt(fromIndexPath: IndexPath, toIndexPath: IndexPath) {
        var items = self.items
        let cardModel = items[fromIndexPath.row]
        items.remove(at: fromIndexPath.row)
        items.insert(cardModel, at: toIndexPath.row)
        self.itemsRelay.accept(items)
    }
    
    public func sendContact() {
        BluetoothManager.shared.clearContact()
        var contacts: [CRPContact] = []
        for (i, contact) in items.enumerated() {
            let model = CRPContact(contactID: i, fullName: contact.fullName, phoneNumber: contact.selectPhoneNumber)
            contacts.append(model)
        }
        BluetoothManager.shared.sendContact(contacts: contacts)
        saveContacts(contacts: items)
    }

    private func saveContacts(contacts: [ContactModel]) {
        
        let newContacts = contacts.map { contactModel in
            let item = ContactModel()
            item.identifier = contactModel.identifier
            item.firstName = contactModel.firstName
            item.lastName = contactModel.lastName
            item.fullName = contactModel.fullName
            item.organizationName = contactModel.organizationName
            item.selectPhoneNumber = contactModel.selectPhoneNumber
            item.phoneNumbers = contactModel.phoneNumbers
            return item
        }
        
        EasepodsDB.deleteAll(type: ContactModel.self)
        
        newContacts.forEach { EasepodsDB.save(object: $0) }
        self.oldContacts = newContacts
        self.itemsRelay.accept(newContacts)
    }
    
    public func isModified() -> Bool {
        guard self.items.count == oldContacts.count else {
            return true
        }
        for i in 0..<self.items.count {
            let contact = self.items[i]
            let oldContact = oldContacts[i]
            if contact.fullName != oldContact.fullName ||
                contact.selectPhoneNumber != oldContact.selectPhoneNumber {
                return true
            }
        }
        return false
    }
}

/*
class AddressBookViewModel: ViewModel {

    public var items: [ContactModel] = []
	private var oldContacts: [ContactModel] = []
    
    /// 最多选择多少个
    public var contactMax: Int = 8
    
    /// 当前选了多少个
    public var currentContactCount: Int = 0
    
    public var contactRelay = BehaviorRelay<[ContactModel]>(value: [])
    
    public func queryDbContact() {
        
        items = EasepodsDB.getAll(type: ContactModel.self)
        self.contactRelay.accept(self.items)
        self.oldContacts = self.items
    }

	public func numberOfRowsInSection() -> Int {
		return items.count
	}

	public func cellModelForRowAtIndexPath(indePath: IndexPath) -> ContactModel {
		let model = items[indePath.row]
		return model
	}

	public func removeCardModel(indexPath: IndexPath) {
        
        let contact = items[indexPath.row]
        items.remove(at: indexPath.row)
	}
    
	public func moveRowAt(fromIndexPath: IndexPath, toIndexPath: IndexPath) {
		let cardModel = items[fromIndexPath.row]
		self.items.remove(at: fromIndexPath.row)
		self.items.insert(cardModel, at: toIndexPath.row)
	}
    
    public func sendContact() {
        BluetoothManager.shared.clearContact()
        var contacts: [CRPContact] = []
        for (i, contact) in items.enumerated() {
            let model = CRPContact(contactID: i, fullName: contact.fullName, phoneNumber: contact.selectPhoneNumber)
            contacts.append(model)
        }
        BluetoothManager.shared.sendContact(contacts: contacts)
        saveContacts(contacts: items)
    }

	public func cleanAllContactAndSaveContacts() {
		sendCleanAllContact()
		saveContacts(contacts: items)
		updateOldContacts()
	}

	public func saveContacts(contacts: [ContactModel]) {
        
        EasepodsDB.deleteAll(objects: oldContacts)
        
        contacts.forEach { contactModel in
            let item = ContactModel(identifier: contactModel.identifier,
                                    firstName: contactModel.firstName,
                                    lastName: contactModel.lastName,
                                    fullName: contactModel.fullName,
                                    organizationName: contactModel.fullName,
                                    selectPhoneNumber: contactModel.selectPhoneNumber)
            EasepodsDB.save(object: item)
        }
        
	}

	public func sendCleanAllContact() {
        oldContacts = []
        BluetoothManager.shared.clearContact()
	}

	func updateOldContacts(isCleanAll: Bool = true) {
		if isCleanAll {
			oldContacts = []
		} else {
			oldContacts = items
		}
	}

	public func isModify(contacts: [ContactModel]) -> Bool {
		guard contacts.count == oldContacts.count else {
			return true
		}
		for i in 0..<contacts.count {
			let contact = contacts[i]
			let oldContact = oldContacts[i]
			if contact.fullName != oldContact.fullName ||
				contact.selectPhoneNumber != oldContact.selectPhoneNumber {
				return true
			}
		}
		return false
	}

	public func inserCardModel(model: ContactModel) {
		items.insert(model, at: 0)
	}
}*/
